import jwt
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from .models import Patient
from django.contrib.auth.hashers import check_password
from .registerForm import RegisterForm
from django.contrib.auth.hashers import make_password
from .PatientUpdateSerializer import PatientUpdateSerializer
import os
from django.utils.timezone import now
from django.conf import settings

from .serializers import PatientSerializer


class AccountRegister(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):
        form = RegisterForm(request.data)  # 传递 request.data 到表单
        print(request.data.get("password"))
        print("测试表单是否有效",form.is_valid())
        if form.is_valid():
            phone = form.cleaned_data['phone']
            password = form.cleaned_data['password']
            name = form.cleaned_data['name']
            gender = form.cleaned_data['gender']
            age = form.cleaned_data['age']
            # 使用 make_password 加密密码
            hashed_password = make_password(password)
            print(hashed_password)

            # 创建新的 Patient 记录
            print("写入数据库")
            Patient.objects.create(phone=phone, password=hashed_password, name=name, gender=gender, age=age)

            # 返回成功响应
            return Response({"message": f"注册成功, 账号为：{phone}"}, status=200)
        else:
            return Response({"message": "注册失败,数据非法或者手机号已经存在"}, status=400)


class AccountLogin(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):
        phone = request.data.get('phone')  # 从请求中获取手机号
        password = request.data.get('password')  # 从请求中获取密码

        try:
            # 通过手机号查找患者记录
            patient = Patient.objects.get(phone=phone)
        except Patient.DoesNotExist:
            return Response({"message": "手机号不存在"}, status=400)

        # 使用 check_password 来验证密码是否正确
        if check_password(password, patient.password):
            # 如果密码正确，生成 JWT token
            refresh = RefreshToken.for_user(patient)
            access_token = str(refresh.access_token)

            # 返回生成的 token
            return Response({
                "message": "登录成功",
                "access_token": access_token,
                "refresh_token": str(refresh)
            }, status=200)
        else:
            # 如果密码错误
            return Response({"message": "密码错误"}, status=400)

# 获取用户信息

class GetUserInfo(APIView):
    def get(self, request):
        # 获取前端传过来的token
        token = request.headers.get('Authorization', None)

        if not token:
            return Response({'error': '未提供Token'}, status=400)

        try:
            # 解码token，获取payload中的user_id
            # token = token.split(' ')[1]  # 去除 Bearer 部分
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            user_id = payload.get('user_id')
            print("用户id为", user_id)



            if not user_id:
                return Response({'error': 'user_id not found in token'}, status=400)

            # 查询数据库，获取user_id对应的年龄
            try:
                user = Patient.objects.get(id=user_id)
                return Response({'user_id': user_id, 'name':user.name,'gender':user.gender,
                                 'addr':user.addr,'account':user.phone,'age': user.age,}, status=200)
            except Patient.DoesNotExist:
                return Response({'error': '查无此人'}, status=404)

        except jwt.ExpiredSignatureError:
            return Response({'error': 'Token has expired,过期啦'}, status=401,)
        except jwt.InvalidTokenError:
            return Response({'error': 'Invalid token,无效'}, status=401)

# 自定义文件名生成函数
# 自定义文件名生成函数
def user_profilephoto_upload_to(instance, filename):
    user_id = instance.id  # 获取 user_id
    ext = filename.split('.')[-1]  # 获取文件的扩展名
    new_filename = f"{user_id}_{now().strftime('%Y%m%d%H%M%S')}.{ext}"  # 文件名以 user_id + 时间戳命名
    return os.path.join('./', new_filename)  # 不要再加 'profile_photos/'，保持路径简洁


class AccountProfilePhoto(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request, *args, **kwargs):
        user_id = request.data.get('user_id')
        # 获取上传的文件
        profilephoto = request.FILES.get('profilephoto')

        if not user_id:
            return Response({"error": "user_id is required"}, status=400)

        if not profilephoto:
            return Response({"error": "profilephoto is required"}, status=400)

        try:
            # 查找 Patient 实例
            patient = Patient.objects.get(id=user_id)
        except Patient.DoesNotExist:
            return Response({"error": "Patient not found"}, status=400)
        if profilephoto:
            patient.profilephoto = profilephoto
            patient.profilephoto.name = user_profilephoto_upload_to(patient, profilephoto.name)
            patient.save()

            # 可以返回新的Patient数据，也可以返回文件路径等信息
            return Response(PatientSerializer(patient).data, status=200)
        return Response({"error": "No profile photo uploaded"}, status=400)


class PatientUpdate(APIView):
    def post(self, request):
        # 获取传入的 id，用来查找医生
        patient_id = request.data.get("patient_id")
        if not patient_id:
            return Response({"detail": "id is required."}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 查找现有医生
            patient =Patient.objects.get(id=patient_id)
        except Patient.DoesNotExist:
            # 如果医生不存在，返回 404
            return Response({"detail": "Doctor not found."}, status=status.HTTP_404_NOT_FOUND)

        # 更新医生信息
        serializer = PatientUpdateSerializer(patient, data=request.data, partial=True)  # partial=True 允许部分更新
        if serializer.is_valid():
            serializer.save()  # 保存更新后的实例
            data ={
                "id": patient.id,
                'patient_name': patient.name,
                'message': "更新成功"
            }

            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

